﻿using CKS.Core.Framework;
using CKS.PLC.Core.Cache;
using CKS.Schedule;
using Infrastructure;
using JinianNet.JNTemplate.Caching;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Infrastructure;
using ZR.Model.Dto.Business.ProductionControl;
using ZR.ServiceCore.Signalr;
using static Org.BouncyCastle.Asn1.Cmp.Challenge;

namespace CKS.PLC.Core.CronJob
{
    /// <summary>
    /// 01大屏推送示例
    /// </summary>
    [Schedule]
    public class Push01Job : CronJobBase
    {
        IHubContext<MessageHub> SignalHub;

        IFreeSql<MesDB> fsql;
        public Push01Job() : base("推送数据服务", "0/1 * * * * ?")  
        {
            fsql = InternalApp.Fsql;
            MessageHub.OnReceiveMessage += MessageHub_OnReceiveMessage;
          
        }

        private void MessageHub_OnReceiveMessage(WebsocketReceiveArg arg)
        {
            switch (arg.Name)
            {
                case "RetryInput":
                    ServiceCommon.ExceptionTasks.Remove(a=>a.Guid == arg.Origin.ToString());
                    break;
                case "ManualInput":
                    ServiceCommon.ExceptionTasks.Remove(a => a.Guid == arg.Origin.ToString());
                    break;
                case "ProductMode":

                    var productMode =arg.Origin.ToInt();
                    Configs.SetValue("Product", (productMode == 1).ToString());
                    InternalApp.DebugMode = productMode == 2;





                    break;

                default:
                    break;
            }
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            /*
              先组织所有的数据，再将数据一次推送给大屏客户端
              本示例数据均为展示需要。 实际项目可能涉及到查询数据库进行统计
              
             */
            SignalHub = InternalApp.ServiceProvider.GetService<IHubContext<MessageHub>>();
            if (SignalHub == null)
                return;
            var statJob =InternalApp.JobProvider.GetService<StatDataJob>();

            await SignalHub.Clients.Clients(MessageHub.Demo01Users)
                .SendAsync("bigScreenDemo01Receive", new { 
                    IsMock=!InternalApp.DebugMode,
                    statJob.OnceTime,
                    statJob.ReceiveCount,
                    statJob.FinishCount,
                    statJob.FinishRate,
                    TaskOrders= statJob.TaskOrders.ToList(),
                    CarboardUsages = statJob.GetCarboardUsages(),
                    WorkData = statJob.GetWorkPositionResponse(),
                    ExceptionTasks = ServiceCommon.ExceptionTasks.ToList().OrderByDescending(a => a.CreatedTime).ToList(),
                });

            await Task.CompletedTask;
        }
    }
}
